import uuid
from django import forms
from BloodSpiderAPI import models
from BloodSpiderModel.DjangoResponseTool.response_dict import response_dict, get_first_error
from BloodSpiderAPI.apis.image import utils as image_utils


# 图片表单
class ImageForm(forms.ModelForm):
    class Meta:
        model = models.AccountImage
        fields = ['description']  # 图片文件单独处理


# 创建图片记录
def create_image(request):
    if request.method != 'POST':
        return response_dict(message="请使用POST请求", code=1)
    
    # 检查必要参数
    aid = request.POST.get('aid')
    uid = request.POST.get('uid')
    
    if not aid or not uid:
        return response_dict(message="账单ID和用户ID为必填项", code=1)
    
    # 检查是否有文件上传
    if 'image' not in request.FILES:
        return response_dict(message="请上传图片文件", code=1)
    
    try:
        # 验证用户和账单存在
        user = models.User.objects.get(uid=uid)
        account = models.Account.objects.get(aid=aid, uid=user)
        
        # 获取图片文件
        image_file = request.FILES['image']
        
        # 创建表单实例
        form = ImageForm(request.POST)
        if not form.is_valid():
            return response_dict(data=get_first_error(form), code=1, message="参数错误")
        
        # 保存图片记录
        image = form.save(commit=False)
        image.iid = uuid.uuid4()
        image.account = account
        image.image = image_file
        image.save()
        
        response = image_utils.utils_model_to_dict(image)
        return response_dict(data=response, message="图片上传成功")
    except models.User.DoesNotExist:
        return response_dict(message="用户不存在", code=1)
    except models.Account.DoesNotExist:
        return response_dict(message="账单不存在或无权限访问", code=1)
    except Exception as e:
        return response_dict(message=f"上传失败: {str(e)}", code=1)


# 获取图片列表
def get_image_list(request):
    if request.method != 'GET':
        return response_dict(message="请使用GET请求", code=1)
    
    # 获取查询参数
    uid = request.GET.get('uid')
    aid = request.GET.get('aid')
    
    # 检查必要参数
    if not uid:
        return response_dict(message="用户ID为必填项", code=1)
    
    try:
        # 验证用户存在
        user = models.User.objects.get(uid=uid)
        
        # 构建查询条件
        filters = {'account__uid': user}
        if aid:
            try:
                account = models.Account.objects.get(aid=aid, uid=user)
                filters['account'] = account
            except models.Account.DoesNotExist:
                return response_dict(message="账单不存在或无权限访问", code=1)
        
        # 查询数据
        images = models.AccountImage.objects.filter(**filters).order_by('-create_time')
        
        # 转换为字典列表
        response_data = []
        for image in images:
            response_data.append(image_utils.utils_model_to_dict(image))
        
        return response_dict(data=response_data, message="获取成功")
    except models.User.DoesNotExist:
        return response_dict(message="用户不存在", code=1)
    except Exception as e:
        return response_dict(message=f"获取失败: {str(e)}", code=1)


# 获取图片详情
def get_image_detail(request, iid):
    if request.method != 'GET':
        return response_dict(message="请使用GET请求", code=1)
    
    # 获取请求用户ID
    uid = request.GET.get('uid')
    if not uid:
        return response_dict(message="用户ID为必填项", code=1)
    
    try:
        # 验证用户存在
        user = models.User.objects.get(uid=uid)
        
        # 获取图片并验证所有权
        image = models.AccountImage.objects.get(iid=iid)
        if image.account.uid != user:
            return response_dict(message="无权限访问该图片", code=1)
        
        response = image_utils.utils_model_to_dict(image)
        return response_dict(data=response, message="获取成功")
    except models.User.DoesNotExist:
        return response_dict(message="用户不存在", code=1)
    except models.AccountImage.DoesNotExist:
        return response_dict(message="图片不存在", code=1)
    except Exception as e:
        return response_dict(message=f"获取失败: {str(e)}", code=1)


# 更新图片记录
def update_image(request, iid):
    if request.method != 'POST':
        return response_dict(message="请使用POST请求", code=1)
    
    # 获取请求用户ID
    uid = request.POST.get('uid')
    if not uid:
        return response_dict(message="用户ID为必填项", code=1)
    
    try:
        # 验证用户存在
        user = models.User.objects.get(uid=uid)
        
        # 获取图片并验证所有权
        image = models.AccountImage.objects.get(iid=iid)
        if image.account.uid != user:
            return response_dict(message="无权限更新该图片", code=1)
        
        # 创建表单实例
        form = ImageForm(request.POST, instance=image)
        if not form.is_valid():
            return response_dict(data=get_first_error(form), code=1, message="参数错误")
        
        # 保存更新后的记录
        updated_image = form.save()
        
        # 如果有新图片上传，更新图片文件
        if 'image' in request.FILES:
            updated_image.image = request.FILES['image']
            updated_image.save()
        
        response = image_utils.utils_model_to_dict(updated_image)
        return response_dict(data=response, message="更新成功")
    except models.User.DoesNotExist:
        return response_dict(message="用户不存在", code=1)
    except models.AccountImage.DoesNotExist:
        return response_dict(message="图片不存在", code=1)
    except Exception as e:
        return response_dict(message=f"更新失败: {str(e)}", code=1)


# 删除图片记录
def delete_image(request, iid):
    if request.method != 'POST':
        return response_dict(message="请使用POST请求", code=1)
    
    # 获取请求用户ID
    uid = request.POST.get('uid')
    if not uid:
        return response_dict(message="用户ID为必填项", code=1)
    
    try:
        # 验证用户存在
        user = models.User.objects.get(uid=uid)
        
        # 获取图片并验证所有权
        image = models.AccountImage.objects.get(iid=iid)
        if image.account.uid != user:
            return response_dict(message="无权限删除该图片", code=1)
        
        # 保存图片路径以便后续可能的清理
        image_path = image.image.path
        image.delete()
        
        # 这里可以添加文件系统清理逻辑
        # import os
        # if os.path.exists(image_path):
        #     os.remove(image_path)
        
        return response_dict(message="删除成功")
    except models.User.DoesNotExist:
        return response_dict(message="用户不存在", code=1)
    except models.AccountImage.DoesNotExist:
        return response_dict(message="图片不存在", code=1)
    except Exception as e:
        return response_dict(message=f"删除失败: {str(e)}", code=1)